// Modules to control application life and create native browser window

// 设置淘宝镜像
// npm config set ELECTRON_MIRROR http://npm.taobao.org/mirrors/electron/

const {app, BrowserWindow, ipcMain} = require('electron')
const express = require("express")
const path = require('path')
let {getCookie, datas} = require('./utils')
const gtk = require('./assets/js/g_tk')

const server = express()
server.use('/', express.static(path.join(__dirname, './assets/web/')))
server.listen(19930, function() {
  console.log("服务开启")
})

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 500,
    height: 350,
    frame: false,
    resizable: false,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('./index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })

  ipcMain.on('login', (event) => {
    let child = new BrowserWindow({
      parent: mainWindow,
      width: 400,
      height: 350,
      title: '登录',
      resizable: false
    })
    const webContents = child.webContents
    webContents.on('will-navigate', async function(e) {
      e.preventDefault()
      await updateGTK()
      event.sender.send('login-success', datas.cookieMap)
      child.close()
    })
    child.setMenu(null)
    child.loadURL('https://xui.ptlogin2.qq.com/cgi-bin/xlogin?proxy_url=http://game.qq.com/comm-htdocs/milo/proxy.html&appid=21000501&target=top&s_url=http%3A%2F%2Fbns.qq.com%2Fcp%2Fa20180725ops%2Findex.htm&style=20&daid=8')
    child.show()
  })
  updateGTK()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  app.quit()
  process.exit(0)
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

// 更新g_tk（用户登陆后）
async function updateGTK() {
  const cookie1 = await getCookie('https://qq.com')
  const cookie2 = await getCookie('https://game.qq.com')
  const cookie = cookie1.concat(cookie2)
  const index = cookie.findIndex(item => item.name === 'skey')
  datas.cookies = cookie.map(item => `${item.name}=${item.value}`).join('; ')
  let cookieO = {}
  cookie.forEach((item, key) => cookieO[item.name] = item.value)
  datas.cookieMap = cookieO
  if (index !== -1) {
    datas.g_tk = gtk(cookie[index].value)
  }
}
